package com.woniu.task;

import com.woniu.util.OssFile;
import com.woniu.util.QiNiuUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;

@Slf4j
@Configuration
public class imageClean {

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0 12 * * ?")
    public void clearImage() throws Exception {
        log.debug("========清除无效图片定时任务开始==========");
        //1.获取两个set集合的差值
        Set<String> difference = redisTemplate.opsForSet().difference("redis_all_upload_image", "redis_db_upload_image");
        //2.遍历集合
        if (difference != null && difference.size() > 0) {
            for (String fileName : difference){
//                //3.调用七牛云的删除方法
//                QiNiuUploadUtils.deleteFile(fileName);
                OssFile.deleteFile(fileName);
                //4.将无效图片的名称从大集合中删除
                redisTemplate.opsForSet().remove("redis_all_upload_image",fileName);
                log.debug("=======删除无效图片: "+fileName+"========");
            }
        }
        log.debug("=========清除无效图片定时任务结束============");

    }
/**
 * 时间长了，redis内存中的数据越来越多，所以要定期清除
 * */
    @Scheduled(cron = "0 0 12 ? * WED")
    public void  clearImaheMax() throws Exception {
        log.debug("==========清空两个集合开始===========");
        //在清空之前要比较一下差值
        clearImage();
        redisTemplate.delete("redis_all_upload_image");
        redisTemplate.delete("redis_db_upload_image");
        log.debug("======清空两个集合结束==========");

    }


}
